﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.Aparts.Web.DataSources;
using blackhouse.BlackApart.Business.Apartments;
using blackhouse.JavaScript.JQuery;
using System.Globalization;
using blackhouse.BlackApart.Business;
using blackhouse.BlackApart.Business.ApartmentServices;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web;
using blackhouse.BlackApart.Web.Navigation;

namespace blackhouse.Aparts.Web.Pages {
    public partial class InterviewerContent : System.Web.UI.Page {

        #region Methods

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            if (!(Request.IsAuthenticated && WebUser.IsInRole("Interviewer")))
                SiteUtils.RedirectToAccessDeniedPage();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
            if (e.Row.RowType == DataControlRowType.DataRow) {
                PostBackOptions pbo = new PostBackOptions(sender as Control, "Select$" + e.Row.RowIndex);
                e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(pbo));
                Page.ClientScript.RegisterForEventValidation(pbo);
                IWebReservation reservation = e.Row.DataItem as IWebReservation;
                if (reservation != null) {
                    HyperLink ctrl = e.Row.Cells[1].Controls[0] as HyperLink;
                    if (ctrl != null) {
                        IApartmentGroup type = reservation.GetGroup();
                        if (type != null) {
                            ctrl.Text = type.ShortName;
                            ctrl.ToolTip = type.Name;
                        }
                    }
                }
            }
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            if (!IsPostBack) {
                GridView1.Sort("departuredate", SortDirection.Descending);
                this.TryPopulateDetailsFromRequest();
            }
            else {
                this.hfStartMenu.Value = "0";
                this.pnlReservationDetails.Visible = false;
            }

            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeFileBasedOnJQuery("blackhouse.Aparts.Web.Scripts.interviewer-content.js,blackhouse.Aparts.Web", true, "");
        }

        private void TryPopulateDetailsFromRequest() {
            if (!string.IsNullOrEmpty(Request.QueryString["reservation"])) {
                int reservationId = 0;
                if (Int32.TryParse(Request.QueryString["reservation"], out reservationId)) {
                    if (reservationId > 0) {
                        IWebReservation reservation = Factory.Instance().GetWebReservation(reservationId);
                        this.PopulateDetailsView(reservation);
                    }
                }
            }
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
            int reservationId = Convert.ToInt32(GridView1.SelectedDataKey.Value);
            IWebReservation reservation = GridView1.SelectedRow.DataItem as IWebReservation;
            if (reservation == null && reservationId > 0) {
                reservation = Factory.Instance().GetWebReservation(reservationId);
                if (reservation != null && reservation.ReservationId != reservationId)
                    reservation = null;
            }
            this.PopulateDetailsView(reservation);
        }

        private void PopulateDetailsView(IWebReservation reservation) {
            if (reservation != null) {
                this.hfStartMenu.Value = "1";
                this.pnlReservationDetails.Visible = true;
                this.ltlReservationNumber.Text = reservation.ReservationNumber;
                this.ltlClientName.Text = this.GetClientName(reservation.Client);
                this.ltlClientPhone.Text = this.FormatClientPhone(reservation.Client);
                this.ltlArrivalDate.Text = reservation.ArrivalDate.ToString("D");
                this.ltlDepartureDate.Text = reservation.DepartureDate.ToString("D");
                this.ltlTotalDays.Text = (reservation.DepartureDate.Date - reservation.ArrivalDate.Date).TotalDays.ToString("F0");
                this.ltlPersonCount.Text = reservation.PersonCount.ToString();
                this.ltlApartment.Text = reservation.GetGroupShortName();
                this.ltlPayCost.Text = reservation.FinalPrice.ToString("C", CultureInfo.GetCultureInfo("pl-PL"));
                this.ltlRabat.Text = string.Format("{0:F0}%", reservation.Rabat);
                if (string.IsNullOrEmpty(reservation.Comments))
                    this.ltlClientOverview.Text = "Brak uwag";
                else
                    this.ltlClientOverview.Text = reservation.Comments.ReplaceEx("/r/n", "<br />");
                if (string.IsNullOrEmpty(reservation.OfficeComments))
                    this.ltlOfficeOverview.Text = "Brak uwag";
                else
                    this.ltlOfficeOverview.Text = reservation.OfficeComments.ReplaceEx("/r/n", "<br />");
                this.ltlAdditionalServices.Text = this.GetReservationServices(reservation);
                this.lnkToAddOpinion.NavigateUrl = string.Format("/pages/addopinion.aspx?addOpinion={0}&reservation={1}", reservation.ReservationId, reservation.Guid);
            }
        }

        private string GetReservationServices(IWebReservation reservation) {
            ReservationAdditionalServicesOrder servicesOrder = new ReservationAdditionalServicesOrder(reservation);
            IEnumerable<ReservationAdditionalService> services = servicesOrder.GetOrderingReservationServices();
            if (services.Count() == 0)
                return "Brak zakupionych usług dodatkowych";
            else {
                List<string> lines = new List<string>();
                foreach (ReservationAdditionalService service in services) {
                    lines.Add(string.Format(CultureInfo.GetCultureInfo("pl-PL"), "{0} * {1} (Koszt: {2:C})", service.Quantity, service.Service.ServiceName, service.Price));
                }
                return string.Join("<br />", lines.ToArray());
            }
        }

        private string FormatClientPhone(IClient client) {
            string phone = client.PhoneNumber.ReplaceEx(" ", "").ReplaceEx("-", "");
            if (phone.Length == 9) {
                return phone.Substring(0, 3) + " " + phone.Substring(3, 3) + " " + phone.Substring(6, 3);
            }
            else
                return client.PhoneNumber;
        }

        private string GetClientName(IClient client) {
            return client.FirstName;
            //List<string> nameParts = new List<string>(2);
            //if (!string.IsNullOrEmpty(client.FirstName))
            //    nameParts.Add(client.FirstName);
            //if (!string.IsNullOrEmpty(client.LastName))
            //    nameParts.Add(client.LastName);
            //return string.Join(" ", nameParts.ToArray());
        }

        #endregion

    }
}